package com.zues.thread.design_mode.guarded_stop;

/**
 * 保护性暂停 模式
 * 保护对象
 * @author zues
 * @date 2021/8/17
 */
public class GuardedObject {

    private Object response;

    public GuardedObject(Integer id) {
        this.id = id;
    }

    //标识GuardedObject
    private Integer id;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    /**
     * 获取结果
     * @param timeout 等待最大时间
     * @return
     */
    public Object get(long timeout) {
        synchronized (this){
            //记录开始时间
            long start = System.currentTimeMillis();
            long duration = 0;
            // 没有结果
            while(response == null){
                try {
                    long waitTime = timeout - duration;
                    //等待时间超出则推出循环
                    if(waitTime <= 0){
                        break;
                    }
                    this.wait(waitTime);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                // 计算过程时间
                duration = System.currentTimeMillis() - start;
            }
            return response;
        }
    }

    /**
     * 产生结果
     * @param response
     */
    public void complete(Object response){
        synchronized (this){
            //给结果成员变量赋值
            this.response = response;
            this.notifyAll();
        }
    }

}
